import React, { useState, useEffect } from 'react';
import { FaUpload, FaTerminal, FaSync, FaCog } from 'react-icons/fa';
import { SSHServiceStatus, ConfigureSSH, OpenTerminal, RestartSSHService } from '../../wailsjs/go/main/App';

const KeyUploader = ({ sshConnected, serverInfo }) => {
  const [status, setStatus] = useState({
    message: '',
    isError: false,
    loading: false
  });

  const [sshConfig, setSSHConfig] = useState({
    sshRunning: false,
    passwordAuthAllowed: false,
    pubkeyAuthAllowed: false,
    disablePassword: false
  });

  useEffect(() => {
    if (sshConnected) {
      checkSSHService();
    }
  }, [sshConnected]);

  const checkSSHService = async () => {
    try {
      const result = await SSHServiceStatus(
        serverInfo.hostname,
        serverInfo.port,
        serverInfo.username,
        serverInfo.password
      );
      setSSHConfig({
        ...sshConfig,
        sshRunning: result.sshRunning,
        passwordAuthAllowed: result.passwordAuthAllowed,
        pubkeyAuthAllowed: result.pubkeyAuthAllowed
      });
      setStatus({ message: result.message, isError: false, loading: false });
    } catch (error) {
      setStatus({ message: `检查SSH服务失败: ${error.message}`, isError: true, loading: false });
    }
  };

  const uploadKey = async () => {
    if (!sshConnected) {
      setStatus({ message: '请先连接服务器', isError: true, loading: false });
      return;
    }

    setStatus({ message: '正在配置SSH...', isError: false, loading: true });
    try {
      const result = await ConfigureSSH(
        serverInfo.hostname,
        serverInfo.port,
        serverInfo.username,
        serverInfo.password,
        sshConfig.disablePassword
      );
      setStatus({ message: result.message, isError: !result.success, loading: false });
    } catch (error) {
      setStatus({ message: `配置失败: ${error.message}`, isError: true, loading: false });
    }
  };

  const restartSSH = async () => {
    setStatus({ message: '正在重启SSH服务...', isError: false, loading: true });
    try {
      const result = await RestartSSHService(
        serverInfo.hostname,
        serverInfo.port,
        serverInfo.username,
        serverInfo.password
      );
      setStatus({ message: result.message, isError: !result.success, loading: false });
      if (result.success) {
        await checkSSHService();
      }
    } catch (error) {
      setStatus({ message: `重启SSH服务失败: ${error.message}`, isError: true, loading: false });
    }
  };

  const openTerminal = async () => {
    try {
      await OpenTerminal(
        serverInfo.hostname,
        serverInfo.port,
        serverInfo.username
      );
      setStatus({ message: '终端已打开', isError: false, loading: false });
    } catch (error) {
      setStatus({ message: `打开终端失败: ${error.message}`, isError: true, loading: false });
    }
  };

  return (
    <div className="key-uploader">
      <h2>上传公钥</h2>
      <div className="server-info">
        <h3>服务器信息</h3>
        <div className="info-grid">
          <div className="info-item">
            <label>主机：</label>
            <span>{serverInfo.hostname || '未设置'}</span>
          </div>
          <div className="info-item">
            <label>端口：</label>
            <span>{serverInfo.port || '22'}</span>
          </div>
          <div className="info-item">
            <label>用户名：</label>
            <span>{serverInfo.username || '未设置'}</span>
          </div>
        </div>
      </div>

      <div className="ssh-config">
        <h3>SSH服务状态</h3>
        <div className="config-grid">
          <div className="config-item">
            <label>SSH服务：</label>
            <span className={sshConfig.sshRunning ? 'success' : 'error'}>
              {sshConfig.sshRunning ? '运行中' : '未运行'}
            </span>
          </div>
          <div className="config-item">
            <label>密码认证：</label>
            <span className={sshConfig.passwordAuthAllowed ? 'success' : 'warning'}>
              {sshConfig.passwordAuthAllowed ? '已启用' : '已禁用'}
            </span>
          </div>
          <div className="config-item">
            <label>公钥认证：</label>
            <span className={sshConfig.pubkeyAuthAllowed ? 'success' : 'error'}>
              {sshConfig.pubkeyAuthAllowed ? '已启用' : '未启用'}
            </span>
          </div>
        </div>
        <div className="config-options">
          <label className="checkbox-label">
            <input
              type="checkbox"
              checked={sshConfig.disablePassword}
              onChange={(e) => setSSHConfig({ ...sshConfig, disablePassword: e.target.checked })}
            />
            配置完成后禁用密码登录
          </label>
        </div>
      </div>

      <div className="button-group">
        <button 
          onClick={uploadKey} 
          disabled={status.loading || !sshConnected} 
          className="primary-button"
        >
          <FaUpload style={{ marginRight: '8px' }} /> 上传并配置
        </button>
        <button 
          onClick={openTerminal}
          disabled={!serverInfo.hostname || !serverInfo.username}
          className="secondary-button"
        >
          <FaTerminal style={{ marginRight: '8px' }} /> 打开终端
        </button>
        <button 
          onClick={restartSSH}
          disabled={status.loading || !sshConnected}
          className="secondary-button"
        >
          <FaSync style={{ marginRight: '8px' }} /> 重启SSH服务
        </button>
      </div>

      {status.message && (
        <div className={`status-message ${status.isError ? 'error' : ''}`}>
          {status.message}
          {status.loading && <span className="loading-spinner"></span>}
        </div>
      )}

      <style jsx>{`
        .key-uploader {
          padding: 2rem;
          background: white;
          border-radius: 1rem;
          box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .server-info, .ssh-config {
          background: #f8fafc;
          border-radius: 0.75rem;
          padding: 1.5rem;
          margin: 1.5rem 0;
        }

        .server-info h3, .ssh-config h3 {
          margin: 0 0 1rem 0;
          font-size: 1.1rem;
          color: #1e293b;
        }

        .info-grid, .config-grid {
          display: grid;
          gap: 1rem;
        }

        .info-item, .config-item {
          display: flex;
          align-items: center;
          gap: 0.5rem;
        }

        .info-item label, .config-item label {
          color: #64748b;
          font-weight: 500;
          min-width: 90px;
        }

        .info-item span {
          color: #0f172a;
          font-family: monospace;
          background: #e2e8f0;
          padding: 0.25rem 0.5rem;
          border-radius: 0.25rem;
          font-size: 0.9rem;
        }

        .config-item span {
          font-weight: 500;
          padding: 0.25rem 0.5rem;
          border-radius: 0.25rem;
          font-size: 0.9rem;
        }

        .config-item span.success {
          background: #dcfce7;
          color: #166534;
        }

        .config-item span.error {
          background: #fee2e2;
          color: #991b1b;
        }

        .config-item span.warning {
          background: #fef3c7;
          color: #92400e;
        }

        .config-options {
          margin-top: 1rem;
          padding-top: 1rem;
          border-top: 1px solid #e2e8f0;
        }

        .checkbox-label {
          display: flex;
          align-items: center;
          gap: 0.5rem;
          color: #475569;
          font-size: 0.9rem;
        }

        .checkbox-label input[type="checkbox"] {
          width: 1rem;
          height: 1rem;
        }

        .button-group {
          display: flex;
          gap: 1rem;
          margin-top: 1.5rem;
          justify-content: center;
          flex-wrap: wrap;
        }

        .status-message {
          margin-top: 1rem;
          text-align: center;
          padding: 1rem;
          border-radius: 0.5rem;
          background: #f1f5f9;
          font-size: 0.9rem;
        }

        .status-message.error {
          background: #fef2f2;
          color: #dc2626;
        }

        @media (max-width: 640px) {
          .button-group {
            flex-direction: column;
          }

          .button-group button {
            width: 100%;
          }
        }
      `}</style>
    </div>
  );
};

export default KeyUploader; 